<template>
<div style="height: 100%">
  <div class="wrapper" >
<!--    style="width: 50%; border: 1px solid #ddd; border-radius: 5px;background-color:#f1f1f1; margin: 0 10px;height: calc(50vh + 125px);"-->

    <!--      聊天内容-->

      <div class="head">
        <div class="headerContent__Ru2XQ">
          <div class="appAvatarInfo__dfT0U">
            <div class="avatarContainer__Qxei8" style="width: 56px; height: 56px; font-size: 56px; line-height: 56px;">
              <img class="avatarImg__Uf110" src="../../assets/logo.png" alt="">
            </div>
            <span class="appName">AI生图！！！</span>
          </div>
          <div class="conversationPrologue__ZLoCQ">
            我是绘画小助手，输入您想绘制画的特征标签
          </div>
        </div>

      </div>
    <div class="im-message-box" v-loading="loading">
      <div v-for="item in messages" :key="item.id">
        <!--           右边的气泡-->
        <div style=" padding-right: 5px;display: flex; align-items: center; "
             v-if="item.fromuser==='me'">
          <div style="align-self: flex-start;">
            <img src="../../assets/user.png" alt="" style="height: 45px; width: 45px; line-height: 40px;border-radius: 50%">
          </div>
          <div class="im-message in-message-right" style="margin-left: 8px;height: 35px; font-size: 18px; line-height: 24px; background-color: #d1ecf6" v-html="item.message"></div>

        </div>
        <!--           左边的气泡-->
        <div style="padding: 5px 0; display: flex; align-items: center; " v-else>
          <div style="align-self: flex-start;">
            <img src="../../assets/logo.png" alt="" style="height: 45px; width: 45px; line-height: 40px; border-radius: 50%;">
          </div>
          <div style=" display: flex; flex-direction: column; margin-left: 8px; " >
            <div style="font-size: smaller">
              绘画小助手
            </div>
            <div class="im-message im-message-left" style="min-height: 33px; display: flex; font-size: 17px; line-height: 24px;
            background-color: #e3ebf5" v-html="item"></div>
          </div>
        </div>
      </div>
    </div>
    <!--       输入区域-->
    <div  class="im-container">
      <div id="im-input">
        <div id="im-content" contenteditable @input="existContent"></div>
        <div class="bottom-right-buttons">
          <el-button v-if="!vis" icon="el-icon-position"  circle @click="send"  ></el-button>
          <el-button v-if="vis" icon="el-icon-position" type="primary" circle @click="send" ></el-button>
        </div>

      </div>

    </div>
  </div>
</div>
</template>

<script>
import SocketService from "@/utils/websocket";

let  socketService;
export default {
  name: "ChatRobot",
  data(){
    return{
      messages: [],
      vis: false,
      user: JSON.parse(localStorage.getItem("user")||'{}'),
      loading: false,
      imageUrl: ""
    }
  },
  mounted() {
    socketService= SocketService.Instance;
    socketService.connect();
    socketService.ws.onmessage= (msg) =>{
        console.log("收到消息",msg.data)
          //后台返回消息后，判断是否是当事人的聊天记录，是就push，避免每发一条就查一次数据库
      // 使用正则表达式替换 \n 为 <br>
      let formattedMessage = msg.data.replace(/\n/g, '<br>');
      formattedMessage = formattedMessage.replace(/!/g, '');
      // 提取并替换图片URL为<img>标签
      const imageUrlRegex = /\[(.*?)\]\((.*?)\)/g;
      formattedMessage = formattedMessage.replace(imageUrlRegex, (match, p1, p2) => {
        // 这里p2是图片URL，将其包裹在<img>标签中
        return '<br><img src="' + p2 + '" alt="' + p1 + '" style="width: 30vh; height: 20vh;"><br>';
      });
          this.loading=false;
          this.messages.push(formattedMessage)

          console.log(this.messages)
          this.scrollToBottom()//滚动页面到底部
    }



  },
  beforeDestroy() {
    if (socketService.ws){
      console.log("关闭websocket连接")
      // socketService.ws.onclose();
      socketService.closelink();
    }
  },
  methods:{
    displayImage(url) {
      // 根据你的应用环境，这里可以是创建img元素、更新现有img的src、或是Vue中绑定src到一个变量等操作
      // 以下是一个简单的示例
      let imgElement = document.createElement('img');
      imgElement.src = url;
      // 然后将这个img元素添加到你的DOM中适当的位置
      // document.getElementById('yourImageContainer').appendChild(imgElement);
      // 或者如果使用Vue，你可能直接赋值给data中的某个属性来触发视图更新
      this.imageUrl = url;
    },
    //发送消息
    send() {
      if (socketService.ws && socketService.ws.readyState === WebSocket.OPEN) {
        let message = this.getMessage('text');
        console.log(message);
        // 发送消息，并在发送后模拟异步处理
        this.sendMessageAsync(socketService.ws, message)
            .then(() => {
              console.log("消息发送成功");
              this.loading=true;
              this.vis=false;
              document.getElementById('im-content').innerHTML = ''; // 清空输入框
            })
            .catch(error => {
              console.error("消息发送失败:", error);
            });
      } else {
        console.error("WebSocket 连接未建立或已关闭，无法发送消息");
      }
    },
    // 模拟异步发送消息方法
    sendMessageAsync(ws, message) {
        // eslint-disable-next-line no-unused-vars
      return new Promise((resolve, reject) => {
        ws.send(JSON.stringify(message));
        this.messages.push(message.msg)
        // 假设消息发送成功，立即resolve，或根据实际情况调整
        resolve();
        // 若要模拟发送失败，可如下处理：
        // ws.onerror = () => reject(new Error("发送过程中发生错误"));
      });
    },
    getMessage(type){
      let inputBox=document.getElementById("im-content")
      const content=inputBox.innerHTML
      if (!content && type==='text'){
        this.$notify.error("请输入内容")
        return
      }
      return{
        msg: {
          fromuser: 'me',
          message: content,
          type: type,
        }
      }
    },
    existContent(){
      let inputBox=document.getElementById("im-content")
      const content=inputBox.innerHTML
      this.vis=content.length>0
    },
    scrollToBottom(){
      this.$nextTick(()=>{
        let imMessageBox=document.getElementsByClassName("im-message-box")[0]
        imMessageBox.scrollTop=imMessageBox.scrollHeight
        console.log('触发滚动')
      })
    },

  }
}

</script>

<style scoped>
.conversationPrologue__ZLoCQ {
  margin-top: 12px;
  padding: 12px 16px;
  border: 1px solid #e8e9eb;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 2px #0000000a;
}
.appName{
  margin-left: 16px;
  color: #151b26;
  font-size: 24px;
  font-weight: 500;
  line-height: 32px;
}
.avatarImg__Uf110 {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.avatarContainer__Qxei8 {
  position: relative;
  flex-shrink: 0;
  border-radius: 50%;
}
.appAvatarInfo__dfT0U {
  display: flex;
}
.wrapper{
  margin-top: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
  height: 100%;
  background-color: #f2f5f9;
  min-width: 1000px;
  overflow: auto;
}
.im-container {
  padding: 10px 0;
  display: flex;
  align-items: center;
}
#im-input {
  position: relative; /* 设置父元素为相对定位，以便子元素可以绝对定位 */
  flex-grow: 1;
  border: 1px solid #ccc;
  padding: 5px;
  min-width: 456px;
  background-color: white;
  border-radius: 25px;
}
#im-content{
  padding-left: 15px;
  outline: none; /* 移除轮廓 */
  line-height: 36px;
  font-size: 18px;
  min-width: 450px;
  max-width: 450px;
  height: 36px;
  display: inline-block;
}
/* 统一按钮样式以减少重复代码 */
.el-button {
  float: right;
  margin-left: 4px; /* 如果需要的话，可以调整按钮之间的间距 */
}
/* 控制按钮的位置 */
.bottom-right-buttons {
  position: absolute;
  bottom: 5px; /* 将按钮定位在底部 */
  right: 5px; /* 将按钮定位在右侧 */
}
.head{
  position: -webkit-sticky;
  position: sticky;
  z-index: 10;
  top: 0;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  box-sizing: border-box;
  width: 100%;
  max-width: 844px;
  padding: 24px 0 24px 0;
}
.im-message{
  margin: 10px 0;
  padding: 5px 10px;
  border-radius: 10px;
}
.im-message-box{
  height: 63vh;
  padding: 10px;
  overflow-y: auto;
  background-color: white;
  width: 850px;
  border-radius: 20px;
}
.im-message-left{
  background-color: #f2f2f2;
}
</style>
